import { uploadParamsType } from '../type';

export function upload(instance: any, params: uploadParamsType) {
  return new Promise((resolve, reject) => {
    const file = params.file;
    if (!file) return reject('未提供上传文件');

    const { maxSize = -1, partSize = -1, queueLength = 1 } = params;

    // 是否采用分片
    const isPart = maxSize > 0 && file.size > maxSize;

    // 中断信号
    params.onCancel && params.onCancel(instance);

    instance
      .multipartUpload(params.fileName, file, {
        progress: (p: any) => {
          params.onUploadProgress &&
            params.onUploadProgress({
              loaded: Math.floor(p * file.size),
              total: file.size,
            });
        },
        parallel: isPart ? queueLength : 1,
        partSize: isPart ? partSize : file.size,
      })
      .then((res: any) => {
        resolve(res);
      })
      .catch((err: any) => {
        reject(err);
      });
  });
}
